"ui";
var version = "v1.0.9";
var jsPath = engines.myEngine().cwd() + "/GongXueYunTask.js";
var xmlPath = engines.myEngine().cwd() + "/ui.xml";

ui.layoutFile(xmlPath);

//设置滑动页面的标题
ui.viewpager.setTitles(["基础配置", "打卡时间", "程序说明"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);
activity.setSupportActionBar(ui.toolbar);

var storage = storages.create("GongxueyunConfig");

let configUsername = storage.get("username");
let configPassword = storage.get("password");
let configHolidays = storage.get("holidays");
let configConsole = storage.get("switchIsShowConsole");

ui.username.setText(configUsername ? configUsername : "");
ui.password.setText(configPassword ? configPassword : "");
ui.holidays.setChecked(configHolidays ? configHolidays : false);
ui.switchIsShowConsole.setChecked(configConsole ? configConsole : false);

let timeStart = storage.get("timeStart");
let timeEnd = storage.get("timeEnd");
if (!timeStart) {
    timeStart = {
        hour: 8,
        minute: 0
    }
}
if (!timeEnd) {
    timeEnd = {
        hour: 17,
        minute: 0
    }
}

ui.timepickerStart.setHour(timeStart["hour"]);
ui.timepickerStart.setMinute(timeStart["minute"]);
ui.timepickerStartText.setText("上班打卡时间（" + timeStart["hour"] + ":" + timeStart["minute"] + "）:");

ui.timepickerEnd.setHour(timeEnd["hour"]);
ui.timepickerEnd.setMinute(timeEnd["minute"]);
ui.timepickerEndText.setText("下班打卡时间（" + timeEnd["hour"] + ":" + timeEnd["minute"] + "）:");


reflesh();

ui.btnRun.click(function () {
    if (ui.btnRun.getText() == "停止任务") {
        removeTask();
        ui.btnRun.setText("保存并启动任务");
        reflesh();
        return;
    }

    if (!ui.autoService.checked) {
        toast("请先开启无障碍服务再重试！");
        return;
    }

    if (!$power_manager.isIgnoringBatteryOptimizations()) {
        toast("未开启忽略电池优化,请开启后再试");
        $power_manager.requestIgnoreBatteryOptimizations();
        return;
    }

    if (ui.switchIsShowConsole.checked && !$floaty.checkPermission()) {
        // 选择开启控制台，但是没有授权悬浮窗权限
        toast("请开启悬浮窗权限后再试");
        return;
    }

    if (!getAppName("com.smilingmobile.practice")) {
        toast("请先安装工学云APP再重试！");
        return;
    }

    storage.put("username", ui.username.text());
    storage.put("password", ui.password.text());
    storage.put("holidays", ui.holidays.checked);
    storage.put("switchIsShowConsole", ui.switchIsShowConsole.checked);
    storage.put("timeStart", {
        "hour": ui.timepickerStart.getHour(),
        "minute": ui.timepickerStart.getMinute()
    });
    storage.put("timeEnd", {
        "hour": ui.timepickerEnd.getHour(),
        "minute": ui.timepickerEnd.getMinute()
    });

    let firstRun = storage.get("firstRun") ? false : true;
    if (firstRun) {
        confirm(title = "第一次启动授权",content="因为第一次启动部分机型(例如小米)需要授权启动，这里先启动一次应用，方便后续自动启动app时不再需要授权。").then(value => {
            if (value) {
                launch("com.smilingmobile.practice");
                storage.put("firstRun", true);
            }
        })
        return;
    }

    confirm(title = "确定启动任务吗？").then(value => {
        //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
        if (value) {
            
            //点击确定
            removeTask();

            let taskStart = $timers.addDailyTask({
                path: jsPath,
                time: ui.timepickerStart.getHour() + ":" + ui.timepickerStart.getMinute(),
                delay: 0,
                loopTimes: 1,
                interval: 0,
            })
            let taskEnd = $timers.addDailyTask({
                path: jsPath,
                time: ui.timepickerEnd.getHour() + ":" + ui.timepickerEnd.getMinute(),
                delay: 0,
                loopTimes: 1,
                interval: 0,
            })
            ui.btnRun.setText("停止任务");
            toast("保存并启动成功");
            reflesh();
        } else {
            //点击取消
            toast("取消启动任务");
        }
    });
});

threads.start(function () {
    let resMainJs = http.get("https://gitee.com/liuhai038/gongxueyun-auto/raw/master/main.js");
    if (resMainJs.statusCode == 200) {
        let resMainJsContent = resMainJs.body.string();
        if (resMainJsContent.indexOf(version) == -1) {
            toast("检测到新版本，请点击更新按钮");
            ui.btnUpdate.setText("检测到新版本，请点击此处更新");
        } else {
            ui.btnUpdate.setText("当前无需更新，可检查更新");
        }
    }
})

ui.btnUpdate.click(function () {
    threads.start(function () {
        let resMainJs = http.get("https://gitee.com/liuhai038/gongxueyun-auto/raw/master/main.js");
        if (resMainJs.statusCode == 200) {
            let resMainJsContent = resMainJs.body.string();
            if (resMainJsContent.indexOf(version) == -1) {
                toast("检测到新版本，正在更新中");
                if (updateVersion(resMainJsContent)) {
                    toast("更新成功！");
                    engines.execScriptFile(engines.myEngine().cwd() + "/main.js", {
                        delay: 2000,
                    });
                    engines.stopAll();
                } else {
                    toast("更新失败");
                }
            } else {
                toast("已是最新版本");
            }
        } else {
            reject("检查更新失败");
        }
    });

});

function updateVersion(resMainContent) {
    let gongxueyunContent = "";
    let resUiXmlContent = "";
    let resGongXueYunTaskJs = http.get("https://gitee.com/liuhai038/gongxueyun-auto/raw/master/GongXueYunTask.js")
    let resUiXml = http.get("https://gitee.com/liuhai038/gongxueyun-auto/raw/master/ui.xml")
    if (resGongXueYunTaskJs.statusCode == 200) {
        gongxueyunContent = resGongXueYunTaskJs.body.string();
    }
    if (resUiXml.statusCode == 200) {
        resUiXmlContent = resUiXml.body.string();
    }
    if (gongxueyunContent && resMainContent && resUiXmlContent) {
        files.write(engines.myEngine().cwd() + "/main.js", resMainContent);
        files.write(engines.myEngine().cwd() + "/GongXueYunTask.js", gongxueyunContent);
        files.write(engines.myEngine().cwd() + "/ui.xml", resUiXmlContent);
        return true;
    } else {
        return false;
    }
}

function removeTask() {
    // 按脚本路径查找定时任务
    let tasks = getAllTasks();
    // 删除查找到的所有定时任务
    tasks.forEach(t => {
        if ($timers.removeTimedTask(t.id)) {
            log("删除定时任务[" + t.id + "]成功");
        }
    });
}

function getAllTasks() {
    let tasks = $timers.queryTimedTasks({
        path: jsPath
    });
    return tasks;
}


// ui.timepickerStart.setIs24HourView(true);
// ui.timepickerEnd.setIs24HourView(true);


ui.timepickerStart.setOnTimeChangedListener(function (timeObject, hour, minute) {
    ui.timepickerStartText.setText("上班打卡时间(" + hour + ":" + minute + "):");
})

ui.timepickerEnd.setOnTimeChangedListener(function (timeObject, hour, minute) {
    ui.timepickerEndText.setText("下班打卡时间(" + hour + ":" + minute + "):");
})

// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启 
//android.permission.SYSTEM_ALERT_WINDOW
ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});

// 用户勾选悬浮窗服务的选项时，跳转到页面让用户去开启 
ui.floatyService.on("check", function (checked) {
    if (!$floaty.checkPermission()) {
        // 没有悬浮窗权限，提示用户并跳转请求
        toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        $floaty.requestPermission();
    } else {
        ui.floatyService.checked = true;
    }
});

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function () {
    reflesh();
});

function reflesh() {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
    ui.floatyService.checked = $floaty.checkPermission();
    let tasks = getAllTasks();
    ui.TaskOneCardTextOne.setText("第一个定时任务：");
    ui.TaskTwoCardTextOne.setText("第二个定时任务：");
    ui.TaskOneCardTextTwo.setText("任务状态：未启动");
    ui.TaskTwoCardTextTwo.setText("任务状态：未启动");

    if (tasks.length > 0) {
        // 当前任务已经存在
        ui.btnRun.setText("停止任务");
        for (let i = 0; i < tasks.length; i++) {
            let task = tasks[i];
            if (i == 0) {
                ui.TaskOneCardTextOne.setText("第一个定时任务(id=" + task.id + ")：")
                ui.TaskOneCardTextTwo.setText("任务状态：已启动")
            } else if (i == 1) {
                ui.TaskTwoCardTextOne.setText("第二个定时任务(id=" + task.id + ")：")
                ui.TaskTwoCardTextTwo.setText("任务状态：已启动")
            }
        }
    }
}